<template>
	<view class="route-container">
		<map id="routeMap" :latitude="startLat" :longitude="startLng" :scale="13" :polyline="polyline"
			:markers="markers" @tap="onMapTap" :include-points="polyline.length ? polyline[0].points : []"
			style="width: 100%; height: 100vh"></map>

		<view class="point-list">
			<view class="point-item" v-for="(point, index) in bypassPoints" :key="index" @click="handleBypass(point)">
				{{ point.name }}
			</view>
		</view>

		<view class="selected-bypass-list" v-if="selectedBypasses.length">
			<view class="bypass-item" v-for="(point, index) in selectedBypasses" :key="'selected-' + index">
				{{ point.name || `绕行点${index + 1}` }}
				<text class="remove-btn" @click="removeBypass(index)">移除</text>
			</view>
		</view>

		<view class="back-button" @click="goBack">返回</view>
	</view>
</template>

<script>
	import {
		TENCENT_MAP_KEY
	} from '@/common/map-key.js';

	export default {
		data() {
			return {
				startLat: null,
				startLng: null,
				endLat: null,
				endLng: null,
				polyline: [],
				markers: [],
				bypassPoints: [{
						name: '中山南路口',
						lat: 31.21001,
						lng: 121.4701
					},
					{
						name: '南京东路口',
						lat: 31.2344,
						lng: 121.4832
					},
					{
						name: '人民广场',
						lat: 31.2303,
						lng: 121.4758
					}
				],
				selectedBypasses: []
			};
		},
		onLoad(options) {
			this.startLat = parseFloat(options.startLat);
			this.startLng = parseFloat(options.startLng);
			this.endLat = parseFloat(options.endLat);
			this.endLng = parseFloat(options.endLng);
			this.getRoute(); // 初始路径
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			getRoute() {
				uni.request({
					// url: 'https://apis.map.qq.com/ws/direction/v1/ebicycling/',
					url: 'http://localhost:8080/direction',
					data: {
						from: `${this.startLat},${this.startLng}`,
						to: `${this.endLat},${this.endLng}`,
						key: TENCENT_MAP_KEY
					},
					success: (res) => {
						console.log(res);
						if (res.data.code === 'Ok') {
							console.log(res);
							this.updatePolylineAndMarkers(res.data.routes[0].geometry.coordinates);
						}
					}
				});
			},
			handleBypass(point) {
				const bypass = {
					id: Date.now() + Math.random(), // 唯一ID
					name: point.name,
					lat: point.lat,
					lng: point.lng
				};
				this.selectedBypasses.push(bypass);
				this.requestRouteWithWaypoints();
			},
			removeBypass(index) {
				this.selectedBypasses.splice(index, 1);
				this.markers = this.markers.filter((marker) => marker.iconPath !== '/static/img/bypass.png'); // 清除绕行标记
				this.selectedBypasses.forEach((point) => {
					this.markers.push({
						id: Date.now(),
						latitude: point.lat,
						longitude: point.lng,
						iconPath: '/static/img/bypass.png',
						width: 24,
						height: 24
					});
				});
				this.requestRouteWithWaypoints();
			},
			onMapTap(e) {
				const midLat = e.detail.latitude;
				const midLng = e.detail.longitude;

				const bypass = {
					id: Date.now() + Math.random(),
					name: '', // 无名点
					lat: midLat,
					lng: midLng
				};
				this.selectedBypasses.push(bypass);
				this.requestRouteWithWaypoints();
			},
			requestRouteWithWaypoints() {
				const allPoints = [{
						lat: this.startLat,
						lng: this.startLng
					},
					...this.selectedBypasses,
					{
						lat: this.endLat,
						lng: this.endLng
					}
				];
				console.log(allPoints);
				this.polyline = [];
				this.markers = [];

				const requests = [];

				for (let i = 0; i < allPoints.length - 1; i++) {
					const from = allPoints[i];
					const to = allPoints[i + 1];

					const request = new Promise((resolve) => {
						uni.request({
							// url: 'https://apis.map.qq.com/ws/direction/v1/ebicycling/',
							url: 'http://localhost:8080/direction',
							data: {
								from: `${from.lat},${from.lng}`,
								to: `${to.lat},${to.lng}`,
								key: TENCENT_MAP_KEY
							},
							success: (res) => {
								console.log(res);
								if (res.data.status === 200) {
									console.log(1);
									const coordinates = res.data.routes[0].geometry
										.coordinates || [];
									const segment = coordinates.map(([lng, lat]) => ({
										latitude: lat,
										longitude: lng
									}));
									console.log("segment",segment);
									resolve(segment);
								} else {
									console.warn('子路径规划失败:', res.data.message);
									resolve([]); // 返回空段防止中断整个路径
								}
							},
							fail: () => resolve([]) // 网络异常处理
						});
					});

					requests.push(request);
				}

				Promise.all(requests).then((segments) => {
					const merged = segments.flat();
					this.polyline = [{
						points: merged,
						color: '#ff6600',
						width: 6
					}];

					// 添加起终点 marker
					this.markers = [{
							id: 1,
							latitude: this.startLat,
							longitude: this.startLng,
							iconPath: '/static/img/start.png',
							width: 32,
							height: 32
						},
						{
							id: 2,
							latitude: this.endLat,
							longitude: this.endLng,
							iconPath: '/static/img/end.png',
							width: 32,
							height: 32
						},
						...this.selectedBypasses.map((p) => ({
							id: p.id,
							latitude: p.lat,
							longitude: p.lng,
							iconPath: '/static/img/bypass.png',
							width: 24,
							height: 24
						}))
					];
				});
			},
			updatePolylineAndMarkers(coordinates) {
					const points = coordinates.map(([lng, lat]) => ({
						latitude: lat,
						longitude: lng
					}));
				
					this.polyline = [{
						points,
						color: '#ff6600',
						width: 6
					}];
				this.markers = [{
						id: 1,
						latitude: this.startLat,
						longitude: this.startLng,
						iconPath: '/static/img/start.png',
						width: 32,
						height: 32
					},
					{
						id: 2,
						latitude: this.endLat,
						longitude: this.endLng,
						iconPath: '/static/img/end.png',
						width: 32,
						height: 32
					},
					// 绕行点 marker 从 selectedBypasses 统一生成
					...this.selectedBypasses.map((p) => ({
						id: p.id,
						latitude: p.lat,
						longitude: p.lng,
						iconPath: '/static/img/bypass.png',
						width: 24,
						height: 24
					}))
				];
			},
			decodePolyline(coors) {
				const kr = 1000000;
				let pl = [];

				for (let i = 2; i < coors.length; i++) {
					coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
				}

				for (let i = 0; i < coors.length; i += 2) {
					pl.push({
						latitude: coors[i],
						longitude: coors[i + 1]
					});
				}

				return pl;
			}
		}
	};
</script>

<style scoped>
	.route-container {
		position: relative;
		width: 100%;
		height: 100vh;
	}

	.back-button {
		position: fixed;
		bottom: 40px;
		left: 20px;
		background-color: #007aff;
		color: white;
		padding: 10px 20px;
		border-radius: 25px;
		z-index: 9999;
	}

	.point-list {
		position: fixed;
		top: 10px;
		right: 10px;
		background: #f6f6f6;
		padding: 10px;
		z-index: 9999;
		border-radius: 10px;
	}

	.point-item {
		padding: 10px;
		background: white;
		margin-bottom: 6px;
		border-radius: 6px;
		font-size: 14px;
		color: #333;
		cursor: pointer;
	}

	.selected-bypass-list {
		position: fixed;
		top: 160px;
		right: 10px;
		background: #fff7e6;
		padding: 10px;
		border-radius: 10px;
		z-index: 9999;
	}

	.bypass-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 6px 8px;
		font-size: 14px;
	}

	.remove-btn {
		color: red;
		font-size: 12px;
		margin-left: 10px;
	}
</style>